const whiteList = ['/login']; //白名单
import router from '@/router/index'
import { store, key } from '@/store/index'
import {getToken,cleanSession} from '@/utils/auth'
router.beforeEach(async(to,from,next) =>{
    //获取token
    let token = getToken();
    if(token){
        if(to.path === '/login' || to.path ==='/'){
            next({path:'/'})
        }else{
            //从vuex里面获取菜单
            let hasRoles = store.state.user.permissions && store.state.user.permissions.length > 0
            if(hasRoles){
                next()
            }else{
                try{
                    //vuex中不存在权限，从服务器获取
                    await store.dispatch('user/getInfo')
                    //获取菜单、动态生成路由
                    await store.dispatch('menu/getMenuList',router)
                    //确保动态添加的路由已经被完全加载上去
                    next({...to,replace:true})
                }catch(error){
                    //重置token
                    cleanSession();
                    //跳到登录
                    next({path:'/login'})
                }
            }
        }
    }else{
        //判断是否在白名单中
        if(whiteList.indexOf(to.path) !== -1){ //存在白名单，放行
            next(); 
        }else{ //不存在，登录
            next({path:'/login'})
        }
    }
})